package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.Expire;
import com.yh.correct.model.Grade;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IGradeService;
import com.yh.correct.service.IJudicialDeptmentService;

/**
 *@author Administrator
 *@注释 : 监管等级控制层
*	
*/
@RestController
@RequestMapping("/grade")
public class GradeController {
	private static Logger logger = LogManager.getLogger(GradeController.class);
	/**
	 * 文件保存路径
	 */
	@Value("${saveDir}")
	private String saveDir;
	/**
	 *@author Administrator
	 *@注释 : 注入监管等级
     *	
     */
	@Autowired
	private IGradeService gradeService;
	/**
	 * 注入司法所服务层接口
	 */
	@Autowired
	private IJudicialDeptmentService jud;
	/**
	 * 注入矫正人员服务层接口
	 */
	@Autowired
	private ICorrectedPersonService cor;
			/**
			 *@author Administrator
			 *@注释 : 增加监管等级
			*	
			*/
		@RequestMapping(value="/add"  )
		public ResultData addGrade(Grade grade){
			int i=0;
			
			try {
				i=gradeService.addGrade(grade);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ResultData rd=new ResultData();
			if(i>0){
				rd.setCode(0);
				rd.setMessage("增加成功！");
			}else{
				rd.setCode(-1);
				rd.setMessage("增加失败！");
			}
			logger.debug("增加监管等级! + GradeController");
			return rd;
		}
		/**
		 * 首页跳转
		 * 
		 * @param 
		 * @return
		 */
		@RequestMapping(value="/skip")
		public ModelAndView skip(){ 
			return new ModelAndView("supervision/grade");
		}
		/**
		 * 增加窗口跳转
		 * 
		 * @param 
		 * @return
		 */
		@RequestMapping(value="/addSkip")
		public ModelAndView addSkip(){ 
			return new ModelAndView("supervision/grade_add");
		}
		/**
		 * 矫正所下拉框显示
		 * 
		 * @param 
		 * @return
		 */
		@RequestMapping(value="/jselect")
		public List<Object> jShowSelect(){ 
			List<Object> list = jud.listJudicialDeptments();
			return list;
		}
		/**
		 * 矫正人员下拉框显示
		 * 
		 * @param 
		 * @return
		 */
		@RequestMapping(value="/pselect")
		public List<CorrectedPerson> pShowSelect(){ 
			List<CorrectedPerson> list = null;
			try {
				list = cor.findCorrectedPerson();
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			return list;
		}
		/**
		 * 矫正人员监管等级下拉框显示
		 * 
		 * @param 
		 * @return
		 */
		@RequestMapping(value="/gra")
		public List<Map<String,Object>> pGrade(){ 
			List<Map<String,Object>>  list = null;
			try {
				list = cor.getAllCorrectedPerson();
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			return list;
		}
		/**
		 *@author Administrator
		 *@注释 : 删除监管等级
		*	
		*/
		@RequestMapping(value="/del" )
		public ResultData delGrade(int id){
			int i=0;
			try {
				i=gradeService.delGrade(id);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ResultData rd=new ResultData();
			if(i>0){
				rd.setCode(0);
				rd.setMessage("删除成功");
			}else{
				rd.setCode(-1);
				rd.setMessage("删除失败！");
			}
			return rd;
		}
		/**
		 *@author Administrator
		 *@注释 : 修改监管等级
		*	
		*/
		@RequestMapping(value="/edit")
		public ResultData editGrade(Grade grade){
			int i=0;
			try {
				i=gradeService.editGrade(grade);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ResultData rd=new ResultData();
			if(i>0){
				rd.setCode(0);
				rd.setMessage("修改成功！");
			}else{
				rd.setCode(-1);
				rd.setMessage("修改失败！");
			}
			logger.debug("修改期满登记! + GradeController");
			return rd;
			
		}
		/**
		 * 修改前查询单条详细监管等级登记
		 * 
		 * @param id
		 * @return
		 */
		@RequestMapping(value="/detail")
		public ModelAndView getaGrade(int id){ 
			logger.debug(id);
			
			Map<String,Object> ex = new HashMap<String,Object>();
					
			try {
				ex =gradeService.getIdGrade(id);
				logger.debug(ex);
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			logger.debug("查询期满登记! + GradeController");
			return new ModelAndView("supervision/grade_edit",ex);
		}
		/**
		 * 查询单条监管等级登记
		 * 
		 * @param id
		 * @return
		 */
		@RequestMapping(value="/getidgrade")
		public ModelAndView getIdGrade(int id){ 
			logger.debug(id);
			Map<String,Object> ex = new HashMap<String,Object>();			
			try {
				ex = gradeService.getIdGrade(id);
				logger.debug(ex);
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			logger.debug("查询单个期满登记! + GradeController");
			return new ModelAndView("supervision/grade_look",ex);
		}
		/**
		 * 模糊查询监管等级
		 * 
		 * @param id
		 * @return
		 */
		@RequestMapping("/get")
		public ResultData getLikeGrade(String name,String jname,Integer pageSize,Integer pageNum){ 
			logger.debug(pageSize);
			Map<String,Object> condition=new HashMap<String,Object>();
			condition.put("pageSize", pageSize);
			condition.put("pageNum", pageNum);
			condition.put("name", name);
			condition.put("jname", jname);
			Page page = null;
			try {
				page = gradeService.getLikeGrades(condition);
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			ResultData rd=new ResultData();
			if(page!=null){
				List<Object> grade= new ArrayList();
				grade.add(page);
				rd.setCode(0);
				rd.setMessage("查询成功！");
				rd.setData(grade);
			}else{
				rd.setCode(-1);
				rd.setMessage("查询失败！");
				
			}
			logger.debug("删除监管等级! + GradeController");
			return rd;
		}
	
		/**
		 * 导出Excle
		 * 
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value="/excel")
		public String outExcle(HttpServletRequest request, HttpServletResponse response){
			String fileName = "监管等级文件";
			List<Map<String, Object>> projects = (List)outData();
			List<Map<String, Object>> list = outExcelRecord(projects);
			String columnNames[] = { "编号", "矫正单位", "姓名", "监管等级", "报到频率", "思想汇报" };
			String keys[] = { "id", "jname", "name", "grade", "frequency","report",};
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			try {
				ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
			} catch (IOException e) {
				e.printStackTrace();
			}
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			try {
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			ServletOutputStream out = null;
			try {
				out = response.getOutputStream();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				bis = new BufferedInputStream(is);
				bos = new BufferedOutputStream(out);
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				try {
					throw e;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				} finally {
				if (bis != null)
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				if (bos != null)
					try {
						bos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
			return null;
		}
		/**
		 * 导出Excle时获取所有信息
		 * 
		 * @return
		 */
		public List<Map<String,Object>> outData(){
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			try {
				list=gradeService.getAllGrade();
				 
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list;
		}
		/**
		 * 记录要导出的所有信息
		 * 
		 * @param projects
		 * @return
		 */
		public List<Map<String, Object>> outExcelRecord(List<Map<String, Object>> projects){
			List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sheetName", "sheet1");
			listmap.add(map);
			Map<String, Object> object = null;
			for (int i = 0; i < projects.size(); i++) {
				object = projects.get(i);
				Map<String, Object> mapValue = new HashMap<String, Object>();
				mapValue.put("id", object.get("id"));
				mapValue.put("jname", object.get("jname"));
				mapValue.put("name", object.get("name"));
				mapValue.put("grade", object.get("grade"));
				mapValue.put("frequency", object.get("frequency"));
				mapValue.put("report", object.get("report"));
	
				listmap.add(mapValue);
			}
			return listmap;
		}
	}


